package elitech.vietnam.myfashion.view;

import java.io.File;
import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.dialog.WarningDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.wsclient.ImageUploader;
import elitech.vietnam.myfashion.wsclient.Service;
import elitech.vietnam.myfashion.wsclient.Utilities;

public class EditProfileView extends LinearLayout implements OnClickListener {

	private static final int NUMCHAR_NAME = 30, NUMCHAR_PROFILE = 60;
	private static final String MEM_DIR = "images/account/" + "";
	public static EditProfileView mInstance = null;

	private MainActivity mContext;
	private Button mBtnSave;
	private EditText mEtUserName, mEtProfile;
	private TextView mTvNumName, mTvNumProfile;
	private ImageView mAvatar;

	String imagePath = "";
	private LinearLayout mMainMenu;

	public EditProfileView(MainActivity context) {
		super(context);
		this.mContext = context;
		mInstance = this;
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (inflater != null) {
			inflater.inflate(R.layout.edit_profile, this);
		}
		this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));

		mAvatar = (ImageView) findViewById(R.id.editprofile_avatar);
		mBtnSave = (Button) findViewById(R.id.editprofile_btnsave);
		mEtUserName = (EditText) findViewById(R.id.editprofile_textboxname);
		mEtProfile = (EditText) findViewById(R.id.editprofile_textboxprofile);
		mTvNumName = (TextView) findViewById(R.id.editprofile_textnamenumchar);
		mTvNumProfile = (TextView) findViewById(R.id.editprofile_textprofilenumchar);
		mMainMenu = (LinearLayout) findViewById(R.id.main_menu);
		mMainMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mContext.callMenu();
			}
		});
		
		if (mContext.mUser == null)
			GetMember();
		else
			LoadView();
//		mContext.changeTitle(mContext.getString(R.string.editprofile), true);
	}

	public void onResume() {

	}

	public void onActivityResult(String imagePath) {
		this.imagePath = imagePath;
		new AsyncTask<Integer, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Integer... params) {
				return Utilities.createScaledImage(
						EditProfileView.this.imagePath,
						MainActivity.IMAGE_TEMP, Const.MAX_THUMB_WIDTH);
			}

			@Override
			protected void onPostExecute(Boolean result) {
				if (result)
					EditProfileView.this.imagePath = MainActivity.IMAGE_TEMP;
				Uri uri = Uri
						.fromFile(new File(EditProfileView.this.imagePath));
				mAvatar.setImageURI(uri);
			}
		}.execute();
	}

	@Override
	protected void onDetachedFromWindow() {
		mInstance = null;
		super.onDetachedFromWindow();
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEtProfile.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(mEtUserName.getWindowToken(), 0);
		
		switch (v.getId()) {
		case R.id.editprofile_avatar:
			new PickDialog(mContext).show();
			break;

		case R.id.editprofile_btnsave:
			if (mEtUserName.getText().length() == 0
					|| !Utilities.checkComment(mEtUserName.getText().toString()))
				new WarningDialog(mContext,
						mContext.getString(R.string.nameblank)).show();
			else
				SaveProfile();
			break;
		}

	}

	private void GetMember() {
		new CallServiceTask() {
			public void work() {
				try {
					mContext.mUser = service.getInfoMemberByID(
							mContext.mUser.Id, -1);
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				if (mContext.mUser != null)
					LoadView();
				else
					mContext.onBackPressed();
			};
		}.execute();
	}

	private void LoadView() {
		UrlImageViewHelper.setUrlDrawable(mAvatar, Const.SERVER_IMAGE_THUMB_URL + mContext.mUser.Image, R.drawable.no_avatar);

		mEtProfile.setText(mContext.mUser.Profile);
		mEtUserName.setText(mContext.mUser.NickName);

		mTvNumName.setText(mContext.mUser.Name.length() + "/" + NUMCHAR_NAME);
		mTvNumProfile.setText(mContext.mUser.Profile.length() + "/"
				+ NUMCHAR_PROFILE);

		mAvatar.setOnClickListener(this);
		mBtnSave.setOnClickListener(this);

		mEtUserName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				String str1 = mEtUserName.getText().toString();
				String str2 = mEtProfile.getText().toString();
				int numchar = str1.length();
				mTvNumName.setText(numchar + "/" + NUMCHAR_NAME);
				if (str1.equals(mContext.mUser.Name)
						&& str2.equals(mContext.mUser.Profile))
					mBtnSave.setEnabled(false);
				else
					mBtnSave.setEnabled(true);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		mEtProfile.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
//				int soLanEnter = mEtProfile.getText().toString().split("\n").length - 1;
//				if (soLanEnter > 1) {
//					mEtProfile.setText(mEtProfile.getText().toString().substring(0, mEtProfile.getText().toString().length() - 1));
//					return;
//				}
				String str1 = mEtUserName.getText().toString();
				String str2 = mEtProfile.getText().toString();
				int numchar = str2.length();
				mTvNumProfile.setText(numchar + "/" + NUMCHAR_PROFILE);
				if (str1.equals(mContext.mUser.Name)
						&& str2.equals(mContext.mUser.Profile))
					mBtnSave.setEnabled(false);
				else
					mBtnSave.setEnabled(true);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		mEtProfile.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event != null 
						&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER
						&& event.getAction() == KeyEvent.ACTION_DOWN
						&& mEtProfile.getText().toString().indexOf("\n")!=-1)
					return true;
				return false;
			}
		});
	}

	private void SaveProfile() {
		new CallServiceTask() {
			int result = -1;

			public void work() {
				String name = mContext.mUser.Id + "_"
						+ System.currentTimeMillis() + ".jpg";
				String image = MEM_DIR + name;

				ImageUploader uploader = new ImageUploader();

				boolean uploadOk = false;
				if (!imagePath.equals(""))
					uploadOk = uploader.upload(imagePath, name, "account");
				else {
					uploadOk = true;
					image = mContext.mUser.Image;
				}
				// mContext.mUser.ImagemContext.mUser.ImagemContext.mUser.ImagemContext.mUser.ImagemContext.mUser.ImagemContext.mUser.ImagemContext.mUser.ImagemContext.mUser.ImagemContext.mUser.Image
				if (uploadOk) {
					Service service = new Service();
					try {
						result = service.editProfile(mContext.mUser.Id,
								mEtUserName.getText().toString(), image,
								mEtProfile.getText().toString());
					} catch (IOException e) {
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						e.printStackTrace();
					}
					if (result > 0)
						mContext.mUser.Image = image;
				}
			};

			protected void onPostExecute(Void result) {
				if (this.result <= 0)
					Toast.makeText(mContext,
							mContext.getString(R.string.connecterror),
							Toast.LENGTH_SHORT).show();
				else {
					Toast.makeText(mContext,
							mContext.getString(R.string.profilesaved),
							Toast.LENGTH_SHORT).show();
					mContext.mUser.NickName = mEtUserName.getText().toString();
					mContext.mUser.Profile = mEtProfile.getText().toString();
					mContext.mEditedInfo = true;
					mContext.onBackPressed();
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private class PickDialog extends android.app.Dialog implements
			View.OnClickListener {
		public PickDialog(Context context) {
			super(context, R.style.Dialog);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.dl_cam);

			this.findViewById(R.id.dl_cam_cam).setOnClickListener(this);
			this.findViewById(R.id.dl_cam_lib).setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			Intent intent = null;
			int request = 0;
			switch (v.getId()) {
			case R.id.dl_cam_cam:
				intent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(MainActivity.IMAGE_TEMP)));
				request = MainActivity.CAMERA_SETTING;
				break;

			case R.id.dl_cam_lib:
				intent = new Intent(Intent.ACTION_PICK,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				request = MainActivity.LIBRAR_SETTING;
				break;

			default:
				break;
			}
			if (intent != null)
				mContext.startActivityForResult(intent, request);
			this.dismiss();
		}

	}

	public EditProfileView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public EditProfileView(Context context) {
		super(context);
	}
}
